// pages/campothers/campothers.js
// import Toast from '@vant/weapp/toast/toast';
const {
  baseURL
} = require("../../utils/request")
const http = require("../../api/index")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    oss_url: baseURL,
    namevalue: '',
    typevalue: '',
    time: '',
    show: false,
    showtime: false,
    error: false,
    checked: true,
    value: '',
    userType: '',
    active: 0,
    index: 0,
    radio: '1',
    list: ['综合营地', '微型营地', '帐篷营地', '教育营地', '运动营地', '无人值守驻车点', ],
    result: [],
    fileList: [],
    steps: [{
        text: '营地信息',
      },
      {
        text: '服务设施',
      },
      {
        text: '营地介绍',
      },
    ],
    columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
    facilitiesList: [],
    selectFacilitiesList: [],
    radio1: '',
    month1: '',
    month2: '',
    years: '',
    id: 1,
    isBoxVisible: false,
  },
  onLoad(options) {
    this.setData({
      userType: options.key
    })
    this.getFacilitiesList()
  },
  //获取服务设施
  async getFacilitiesList() {
    const res = await http.serviceFacilities()
    this.setData({
      facilitiesList: res.data
    })
    console.log(res)
  },
  //选中服务设施
  selectIcon(e) {
    let a, b, select, list, id, data
    list = this.data.facilitiesList
    id = e.currentTarget.dataset.id
    data = this.data.selectFacilitiesList
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i
          b = j
        }
      }
    }
    select = list[a].facilities[b].state

    //如果没有选中
    if (select == 1) {
      list[a].facilities[b].state = 2
      data.push(id)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      })
    } else {
      list[a].facilities[b].state = 1
      let index = data.indexOf(id)
      data.splice(index, 1)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data,
      })
    }
    console.log(this.data.selectFacilitiesList);
  },
  //弹出层
  showPopup() {
    this.setData({
      show: true,
    });
  },
  showPopup1() {
    this.setData({
      showTime: true,
    });
  },
  inputChange1(e) {
    this.setData({
      month1: e.detail.value
    });
  },
  inputChange2(e) {
    this.setData({
      month2: e.detail.value
    });
  },
  submint() {
    const radio = this.data.radio1;
    const one = "1"
    const two = "2"
    if (radio == one) {
      this.setData({
        time: "全年",
        month1: '',
        month2: ''
      })
      this.onClose2()
    }
    if (radio == two) {
      this.setData({
        time: this.data.month1 + this.data.month2
      })
      this.onClose2()
    }
  },
  //弹出层
  onClose() {
    this.setData({
      show: false
    });
  },
  onClose2() {
    this.setData({
      showTime: false
    });
  },

  //选择器
  onChange(e) {
    const {
      picker,
      value,
      index
    } = e.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({
      index: index,
      typevalue: this.data.columns[index]
    })

  },
  //控制滑动器
  onChange1({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      checked: detail
    });
  },
  onConfirm() {
    this.setData({
      show: false,
    });
  },
  onChanel() {
    this.setData({
      typevalue: '',
    });
    this.onConfirm();
  },
  //提示信息
  onInput(event) {
    // 更新输入框的值
    this.setData({
      namevalue: event.detail,
      error: false // 当有输入时，隐藏错误提示
    });
  },

  onBlur() {
    // 当输入框失去焦点且没有输入内容时，显示错误提示
    if (!this.data.namevalue.trim()) {
      this.setData({
        error: true
      });
    }
  },
  //控制滑动器
  onChange1({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      checked: detail
    });
  },

  //文件上传
  afterRead(event) {
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: '', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        user: 'test'
      },
      success(res) {
        // 上传完成需要更新 fileList
        const {
          fileList = []
        } = this.data;
        fileList.push({
          ...file,
          url: res.data
        });
        this.setData({
          fileList
        });
      },
    });
  },

  camptypeTap() {
    wx.navigateTo({
      url: '/pages/camptype/camptype'
    })
  },
  camptimeTap() {
    wx.navigateTo({
      url: '/pages/camptime/camptime'
    })
  },
  // 营地位置
  selectSite() {
    // 检查用户权限状态
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          // 用户尚未授权或已拒绝授权
          // 主动请求授权
          this.requestLocationAuthorization();
        } else {
          // 已经授权，直接获取位置信息
          this.getUserLocation();
        }
      }
    })
  },
  //获取位置信息
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        console.log(res, "返回的数据")
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.chooseLocation({
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          success: (res) => {
            console.log(res, '########');
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              campLocation: res.address
            });
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
      },
      complete: () => {
        console.log('位置获取操作已完成');
      }
    });
  },
  // 请求授权
  requestLocationAuthorization() {
    // 请求用户授权精确位置
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getUserLocation();
      },
      fail: (err) => {
        // 拒绝授权，提示用户收到开启
        this.showSettingPrompt()
      }
    })
  },
  showSettingPrompt() {
    wx.showModal({
      title: '需要位置权限',
      content: '请在设置中开启位置权限以正常使用本功能。',
      showCancel: false,
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting['scope.userLocation']) {
                // 用户在设置中开启了位置权限
                this.getUserLocation();
              } else {
                // 用户仍然拒绝位置权限
                console.log('用户仍未开启位置权限');
              }
            },
          });
        }
      },
    });
  },
  // 单选框
  onChange2(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onclick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    const vi = "2"
    if (name == vi) {
      this.data.isBoxVisible = true
    }
    this.setData({
      radio1: name
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */

  //切换到下一页
  onNextStep: function () {
    // 点击按钮时调用的方法，切换到下一个步骤
    if (this.data.active < 2) {
      this.setData({
        active: this.data.active + 1
      });
    }
  },

  onPerStep: function () {
    // 点击按钮时调用的方法，切换到下一个步骤
    if (this.data.active > 0) {
      this.setData({
        active: this.data.active - 1
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})